package com.ruitaowang.admin.view.api;

import com.ruitaowang.core.domain.District;
import com.ruitaowang.core.web.BaseController;
import com.ruitaowang.core.web.MsgOut;
import com.ruitaowang.goods.service.DistrictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by neal on 11/17/16.
 */
@RestController
public class APIDistrictController extends BaseController {

    protected final Logger LOGGER = LoggerFactory.getLogger(getClass());

    @Autowired
    private DistrictService districtService;

    @RequestMapping("/api/districts")
    public String list(District district) {
        MsgOut o = MsgOut.success(districtService.select(district));
        return this.renderJson(o);
    }
    @RequestMapping("/api/admin/districts")
    public String adminDistrictsId(Long id) {
        MsgOut o = MsgOut.success(districtService.selectByPK(id));
        return this.renderJson(o);
    }
    /**
     * @api {get} /api/districts/page 地址查询（级联）
     * @apiVersion 0.1.0
     * @apiSampleRequest /api/districts/page
     *
     * @apiName listForPage
     * @apiGroup 地址
     *
     * @apiParam {int} page 第几页.
     * @apiParam {int} rows 每页条数.
     * @apiParam {long} parentid 父级ID.（0 = 省）
     *
     * @apiSuccess {int} code 接口返回状态码.
     * @apiSuccess {String} msg  接口返回信息.
     * @apiSuccess {Object} data  接口返回数据.
     *
     * @apiSuccessExample Success-Response:
     *     HTTP/1.1 200 OK
     *
     *    {
     *       "code":0,
     *       "data":[
     *           {
     *                    0:{bizUserId: 0, cityUserId: 0, code: "340300", ctime: 0, districtOrder: 3, id: 221, initial: "0",…}
     *                   "bizUserId":1502870415259,
     *                   "id":8,
     *                   "cityUserId":0,
     *                   "code":"",
     *                   "districtOrder":0,
     *                   "initial":"",
     *                   "initials":"",
     *                   "goodsId":0,
     *                   "mtime":1502870415259,
     *                   "remark":"",
     *                   "name":"",
     *                   "parentid":6,
     *                   "pinyin":"",
     *                   "price":6,
     *                   "suffix":6,
     *                   "used":6,
     *                   1:{bizUserId: 0, cityUserId: 0, code: "341500", ctime: 0, districtOrder: 13, id: 231, initial: "0",…}
     *                   2:{bizUserId: 0, cityUserId: 0, code: "341500", ctime: 0, districtOrder: 13, id: 231, initial: "0",…}
     *                   3:{bizUserId: 0, cityUserId: 0, code: "341500", ctime: 0, districtOrder: 13, id: 231, initial: "0",…}
     *                   4:{bizUserId: 0, cityUserId: 0, code: "341500", ctime: 0, districtOrder: 13, id: 231, initial: "0",…}
     *                   5:{bizUserId: 0, cityUserId: 0, code: "341500", ctime: 0, districtOrder: 13, id: 231, initial: "0",…}
     *                   ......
     *           }
     *       ],
     *       "msg":"操作成功啦",
     *       "records":5,
     *       "title":"成功",
     *       "total":1,
     *       "type":"SUCCESS"
     *    }
     *
     * @apiError InternalServerError.
     *
     * @apiErrorExample Error-Response:
     *     HTTP/1.1 500 Internal Server Error
     *  {
     *      "timestamp":1504064947603,
     *      "status":500,
     *      "error":"Internal Server Error",
     *      "exception":"java.lang.ArithmeticException",
     *      "message":"/ by zero",
     *      "path":"/api/districts/page"
     *  }
     */
    @RequestMapping("/api/districts/page")
    public String listForPage(District district, int page) {
        district.setPage(page);
        district.setOrderBy("mtime asc");
        MsgOut o = MsgOut.success(districtService.selectForPage(district));
        o.setRecords(district.getRecords());
        o.setTotal(district.getTotal());
        return this.renderJson(o);
    }

    @RequestMapping("/api/wap/districts")
    public String wapListForPage(District district) {
        district.setOrderBy("id asc");
        MsgOut o = MsgOut.success(districtService.select(district));
        return this.renderJson(o);
    }

    /**
     * 获取地区列表
     * @param district
     * @return
     */
    @RequestMapping("/api/wap/districts/selectAll")
    public String wapListForCity(District district) {
        Map map = new HashMap();
        List<District> districts = districtService.selectByName(district);
        List<District> districtRepeat=districtService.selectRepeat(district);
        for(District d : districts){
            for (District dr : districtRepeat){
                d.setPinyin(d.getPinyin().substring(0,1));
                if (d.getId().equals(dr.getId())){
                    LOGGER.info("进入此方法了！");
                    d.setName(dr.getName());
                }
            }
        }
        map.put("companyCount",districts.size());
        map.put("districts",districts);
        MsgOut o = MsgOut.success(map);
        return this.renderJson(o);
    }
    /**
     * 根据地址名称获取地址Id
     * @param province
     * @param city
     * @param district
     * @return
     */
    @RequestMapping("/api/wap/districts/getName")
    public String wapName(String province,String city,String district) {
        Map<String, Object> map = new HashMap<>();
        District district1 = new District();
        District district2 = new District();
        District district3 = new District();
        district1.setName(province);
        List<District> districts1 = districtService.select(district1);
        long provinceId = districts1.get(0).getId();
        long cityId;
        long districtId;
        long districtIds;
        district1.setName(province);
        try {
            if(province == city || province.equals(city)){
                LOGGER.info("进入方法！");
                cityId = provinceId;
                district2.setName(district);
                district2.setParentid(provinceId);
                List<District> districts2 = districtService.select(district2);
                districtId = districts2.get(0).getId();
            } else {
                district2.setName(city);
                district2.setParentid(provinceId);
                List<District> districts2 = districtService.select(district2);
                cityId = districts2.get(0).getId();
                district3.setName(district);
                district3.setParentid(cityId);
                List<District> districts3 = districtService.select(district3);
                districtId = districts3.get(0).getId();
            }
            districtIds = districtId;
            map.put("provinceId",provinceId);
            map.put("cityId",cityId);
            map.put("districtId",districtId);
            map.put("districtIds",districtIds);
            map.put("province",province);
            map.put("city",city);
            map.put("district",district);
            MsgOut o = MsgOut.success(map);
            return this.renderJson(o);
        } catch (Exception e) {
            return this.renderJson(MsgOut.error("address error."));
        }
    }


    @RequestMapping(value = "/api/districts", method = RequestMethod.POST)
    public String create(District district) {

        districtService.insert(district);
        MsgOut o = MsgOut.success(district);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/districts", method = RequestMethod.PUT)
    public String update(District district) {

        districtService.update(district);
        MsgOut o = MsgOut.success(district);
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/districts/{districtId}", method = RequestMethod.DELETE)
    public String delete(@PathVariable("districtId") Long districtId) {

        MsgOut o = MsgOut.success(districtService.delete(districtId));
        return this.renderJson(o);
    }

    @RequestMapping(value = "/api/wap/districts/city", method = RequestMethod.GET)
    public String findCityDistricts() {
        District district=new District();
//        HashMap map = new HashMap();
        List outList = new ArrayList();
        List<District> districts=districtService.selectByCity(district);
        for (int i=0; i<26; i++) {
            List<District> cityList = new ArrayList<>();
            if ("B".equals(String.valueOf((char)(65+i)))){
                District beijing= new District();
                beijing.setId(1L);
                beijing.setName("北京市");
                beijing.setPinyin("beijing");
                cityList.add(beijing);
            }else if ("T".equals(String.valueOf((char)(65+i)))){
                District tianjin= new District();
                tianjin.setId(2L);
                tianjin.setName("天津市");
                tianjin.setPinyin("tianjin");
                cityList.add(tianjin);
            }else if ("S".equals(String.valueOf((char)(65+i)))){
                District shanghai= new District();
                shanghai.setId(3L);
                shanghai.setName("上海市");
                shanghai.setPinyin("shanghai");
                cityList.add(shanghai);
            }else if ("C".equals(String.valueOf((char)(65+i)))){
                District chongqing= new District();
                chongqing.setId(4L);
                chongqing.setName("重庆市");
                chongqing.setPinyin("chongqing");
                cityList.add(chongqing);
            }
            for (District d:districts){
                if (String.valueOf((char)(65+i)).equals(d.getPinyin().substring(0,1).toUpperCase())){
                    cityList.add(d);
                }
            }
//            if (!ObjectUtils.isEmpty(cityList)){
//                map.put(String.valueOf((char)(65+i)),cityList);
//            }
            outList.add(i,cityList);
        }
        MsgOut o = MsgOut.success(outList);
        return this.renderJson(o);
    }
}